﻿using NewLife;
using NewLife.Data;
using NewLife.Log;
using NewLife.Net;
using NewLife.Serialization;
using System.IO.Compression;
using System.Text;
using System.Text.Json;

namespace NetServer;

/// <summary>定义服务端，用于管理所有网络会话</summary>
internal class MyNetServer : NetServer<MyNetSession>
{
}

/// <summary>定义会话。每一个远程连接唯一对应一个网络会话，再次重复收发信息</summary>
internal class MyNetSession : NetSession<MyNetServer>
{
    /// <summary>
    /// 客户端连接
    /// </summary>
    protected override void OnConnected()
    {
        // 发送欢迎语
        Send($"Welcome to visit {Environment.MachineName}! 客户端： [{Remote}]\r\n");

        base.OnConnected();
    }

    /// <summary>
    /// 客户端断开连接
    /// </summary>
    [Obsolete]
    protected override void OnDisconnected()
    {
#if DEBUG
        WriteLog("客户端{0}已经断开连接", Remote);
#endif

        base.OnDisconnected();
    }

    /// <summary>收到客户端数据</summary>
    /// <param name="e"></param>
    protected override void OnReceive(ReceivedEventArgs e)
    {
        //WriteLog("日志集中存储服务收到了，日志内容：{0}", e.Packet.ToStr());

        // 对解开的数据包e.Packet进行业务处理
        var packet = (Packet)e.Packet;

        if (e.Message as Packet != null)
        {
            packet = e.Message as Packet;
            //return;
        }

        if (packet != null)
        {
            //var obj2 = Binary.FastRead<LogPacketInfo>(packet.GetStream());
            WriteLog("Message:[{0}],Packet:{1}", e.Message, e.Packet.Data);
            return;
            string fileDataText = Encoding.UTF8.GetString(packet.ToArray());
            //LogPacketInfo receivedLogPacketInfo = JsonSerializer.Deserialize<LogPacketInfo>(fileDataText);
            // 解压缩字节数组为LogPacketInfo对象
            LogPacketInfo receivedLogPacketInfo = DecompressLogPacketInfo(packet.Data.ToArray());

            //var itemTuple = GetLogName(packet.ToArray());
            //string fileName = itemTuple.Item1;
            ////Console.WriteLine($"文件名: {fileName}");

            //// 检查第一个字节来判断是否是新增文件
            //var IsNewFileBytes = new byte[1];
            //Array.Copy(packet.ToArray(), 0, IsNewFileBytes, 0, 1);

            //if (GetUTF8Name(IsNewFileBytes) == "1")
            //{
            //    // 新增文件
            //    XTrace.WriteLine($"新增文件{fileName}");
            //    // 处理文件数据，例如保存到磁盘
            //    FileOperation.CreateFile($"D:\\ACCT\\logcenter\\127.0.0.1\\diss\\{fileName}");

            //    // FileOperation.WriteData($"D:\\ACCT\\logcenter\\{fileName}", fileDataText);
            //}
            //else
            //{
            //    // 获取文件数据
            //    var fileDataLength = packet.ToArray().Length - itemTuple.Item2;
            //    var fileDataBytes = new byte[fileDataLength];
            //    Array.Copy(packet.ToArray(), itemTuple.Item2 - 1, fileDataBytes, 0, fileDataLength);
            //    byte[] fileData = fileDataBytes;
            //    string fileDataText = Encoding.UTF8.GetString(fileData);

            //    if (fileData == null) return;
            //    // 非新增文件
            //    XTrace.WriteLine($"更新文件{fileName}，具体内容: {fileDataText}");
            //    FileOperation.WriteData($"D:\\ACCT\\logcenter\\127.0.0.1\\diss\\{fileName}", fileDataText);
            //}
            //var packetData = e.Packet.ToStr();

            //Send($"已经处理完数据:{packetData}");
        }
        else
        {
            Console.WriteLine("No packet received.");
        }
    }

    /// <summary>出错</summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected override void OnError(object sender, ExceptionEventArgs e)
    {
#if DEBUG
        WriteLog("[{0}]错误：{1}", e.Action, e.Exception?.GetTrue().Message);
#endif

        base.OnError(sender, e);
    }

    private static Tuple<string, int> GetLogName(byte[] date)
    {
        byte[] packetData = date;
        int nameStartIndex = 1; // 假设名字从数组的开始位置开始
        int nameEndIndex = 0;
        string filename = string.Empty;

        // 寻找.log的出现位置
        for (int i = 0; i < packetData.Length; i++)
        {
            if (packetData[i] == '.' && packetData[i + 1] == 'l' && packetData[i + 2] == 'o' && packetData[i + 3] == 'g')
            {
                nameEndIndex = i + 3 + 1;
                break;
            }
        }

        // 确保找到了.log
        if (nameEndIndex > 0)
        {
            byte[] nameBytes = new byte[nameEndIndex - nameStartIndex];
            Array.Copy(packetData, nameStartIndex, nameBytes, 0, nameEndIndex - nameStartIndex);

            // 这里可以处理 nameBytes 数组，比如解析出日志名称
            filename = GetUTF8Name(nameBytes);
        }

        return new Tuple<string, int>(filename, nameEndIndex + 1);
    }

    private static string GetUTF8Name(byte[] nameBytes)
    {
        return Encoding.UTF8.GetString(nameBytes);
    }

    public static LogPacketInfo DecompressLogPacketInfo(byte[] compressedData)
    {
        // 解压缩字节数组
        using (MemoryStream memoryStream = new MemoryStream(compressedData))
        {
            using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
            {
                using (StreamReader reader = new StreamReader(gzipStream))
                {
                    string json = reader.ReadToEnd();
                    // 将JSON字符串反序列化为LogPacketInfo对象
                    return JsonSerializer.Deserialize<LogPacketInfo>(json);
                }
            }
        }
    }

    public record LogPacketInfo
    {
        /// <summary>
        /// 是否新增文件
        /// </summary>
        public bool IsNewFile { get; set; }

        /// <summary>
        /// 文件名称
        /// </summary>
        public required string FileName { get; set; }

        /// <summary>
        /// 进程
        /// </summary>
        public required int ProgressType { get; set; }

        /// <summary>
        /// 文件具体内容
        /// </summary>
        public byte[]? Data { get; set; }
    }
}